<template>
  <view class="workbench-container">
    <view v-if="!warehouseId || warehouseId === 0" class="no-warehouse-tip">
      <text class="tip-text">您尚未绑定仓库</text>
      <text class="tip-subtitle">请联系管理员分配所属仓库</text>
    </view>
    <view v-else>
      <view class="workbench-tabs">
        <view 
          class="tab-item" 
          :class="{ 'active': activeTab === '我的任务' }"
          @click="activeTab = '我的任务'"
        >我的任务</view>
        <view 
          class="tab-item" 
          :class="{ 'active': activeTab === '接单中心' }"
          @click="activeTab = '接单中心'"
        >接单中心</view>
      </view>

      <!-- 我的任务 -->
      <view v-if="activeTab === '我的任务'" class="order-list">
        <view 
          v-for="(order, index) in sortedOrderList" 
          :key="index" 
          class="order-item"
          :class="{
            'order-status-pending': order.status === 0,
            'order-status-ontime': order.status === 1,
            'order-status-delayed': order.status === 2
          }"
          style="position: relative;"
        >
          <view class="order-header">
            <text class="order-number">订单号：{{ order.orderId }}</text>
            <view class="order-header-right">
              
              <text 
                class="order-status-text order-status-bold"
                :class="{
                  'order-status-pending': order.status === 0,
                  'order-status-ontime': order.status === 1,
                  'order-status-delayed': order.status === 2
                }"
              >
                {{ getOrderStatusText(order.status) }}
              </text>
            </view>
          </view>
          
          <view class="order-content">
            <view class="order-location">
              <text class="location-text">
                {{ order.cityName }}{{ order.districtName }}{{ order.address }}
              </text>
            </view>
            
            <view class="order-contact">
              <text class="contact-name">
                {{ order.userName || '未知用户' }}
              </text>
              <text class="contact-phone">
                {{ order.phone || '未知电话' }}
              </text>
            </view>
            
            <view class="order-details">
              <text class="order-distance">配送距离：{{ order.distance }}km</text>
            </view>
          </view>
          
          <view class="order-actions">
            <text 
              v-if="order.status === 0" 
              class="action-btn complete-btn"
              @click="completeOrder(order)"
            >完成配送</text>
            <text 
              v-if="order.status === 1" 
              class="action-btn completed-btn"
            >准时送达</text>
            <text 
              v-if="order.status === 2" 
              class="action-btn delayed-btn"
            >超时送达</text>
          </view>
          <view v-if="order.status === 0 && order.startDeliveryTime" class="order-timer-box">
            <text :class="{'overtime': isOrderOvertime(order)}">
              {{ getOrderTimerText(order) }}
            </text>
          </view>
        </view>
      </view>

      <!-- 接单中心 -->
      <view v-else-if="activeTab === '接单中心'" class="order-center">
        <view class="order-center-header">
          <text class="order-center-title">可接单数量：{{ availableOrderCount }}</text>
        </view>
        
        <view class="available-order-list">
          <view 
            v-for="(order, index) in availableOrders" 
            :key="index" 
            class="order-item available-order"
            :class="{'order-selected': isOrderSelected(order)}"
          >
            <view class="order-header">
              <text class="order-number">订单号：{{ order.orderId }}</text>
              <text class="order-time">{{ order.createTime }}</text>
            </view>
            
            <view class="order-content">
              <view class="order-location">
                <text class="location-text">
                  {{ order.cityName }}{{ order.districtName }}{{ order.address }}
                </text>
              </view>
              
              <view class="order-contact">
                <text class="contact-name">
                  {{ order.userName || '未知用户' }}
                </text>
                <text class="contact-phone">
                  {{ order.phone || '未知电话' }}
                </text>
              </view>
              
              <view class="order-details">
                <text class="order-distance">配送距离：{{ order.distance }}km</text>
              </view>
            </view>
            
            <view 
              class="order-checkbox" 
              @click="toggleOrderSelection(order)"
            >
              <text 
                class="checkbox" 
                :class="{'checked': isOrderSelected(order)}"
              ></text>
            </view>
          </view>
        </view>
        
        <!-- 底部选择栏 -->
        <view class="bottom-selection-bar">
          <view 
            class="select-all-btn" 
            @click="toggleSelectAllOrders"
          >
            <text 
              class="checkbox" 
              :class="{'checked': isAllOrdersSelected}"
            ></text>
            <text>全选</text>
          </view>
          <text 
            class="receive-all-btn" 
            @click="receiveSelectedOrders"
            :class="{'disabled': selectedOrders.length === 0}"
          >一键接单</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request'

export default {
  data() {
    return {
      activeTab: '我的任务',
      // 静态测试数据：我的任务
      mockOrderList: [],
      // 静态测试数据：接单中心
      mockAvailableOrders: [],
      orderList: [],
      availableOrders: [],
      availableOrderCount: 0,
      selectedOrders: [],
      isAllOrdersSelected: false,
      warehouseId: '',
      warehouseName: '',
      timerInterval: null
    }
  },
  computed: {
    sortedOrderList() {
      if (!this.orderList) return []
      // 配送中（0）最上，准时送达（1）中间，超时送达（2）最下，组内按创建时间倒序
      return this.orderList.slice().sort((a, b) => {
        // 先按状态排序
        const statusOrder = [0, 1, 2]
        const aStatusIdx = statusOrder.indexOf(a.status)
        const bStatusIdx = statusOrder.indexOf(b.status)
        if (aStatusIdx !== bStatusIdx) return aStatusIdx - bStatusIdx
        // 同组内按创建时间倒序
        return new Date(b.createTime) - new Date(a.createTime)
      })
    }
  },
  onShow() {
    // 获取本地存储的用户信息，判断是否绑定仓库
    const userInfo = uni.getStorageSync('courierUserInfo')
    if (userInfo && userInfo.warehouseId) {
      this.warehouseId = userInfo.warehouseId
      this.warehouseName = userInfo.warehouseName
    } else {
      this.warehouseId = ''
      this.warehouseName = ''
    }
    this.fetchOrderList()
    this.fetchAvailableOrders()
  },
  mounted() {
    this.startOrderTimers();
  },
  beforeDestroy() {
    clearInterval(this.timerInterval);
  },
  methods: {
    getOrderStatusText(status) {
      switch(status) {
        case 0: return '配送中'
        case 1: return '准时送达'
        case 2: return '超时送达'
        default: return '未知状态'
      }
    },
    async fetchOrderList() {
      try {
        // 尝试获取真实数据
        const res = await request({
          url: '/courier/my-orders',
          method: 'GET',
          data: {
            courierAccount: uni.getStorageSync('courierAccount')
          }
        })
        
        if (res.code === 200 && res.data && res.data.length > 0) {
          this.orderList = res.data
        } else {
          // 如果没有真实数据，使用静态mock数据
          console.warn('没有获取到真实订单数据，使用静态mock数据')
          this.orderList = this.mockOrderList
        }
      } catch (err) {
        console.error('获取我的任务订单失败:', err)
        // 发生错误时使用静态mock数据
        this.orderList = this.mockOrderList
        
        uni.showToast({
          title: '获取订单失败，使用测试数据',
          icon: 'none'
        })
      }
    },
    async fetchAvailableOrders() {
      try {
        // 尝试获取真实数据
        const res = await request({
          url: '/courier/available-orders',
          method: 'GET',
          data: {
            courierAccount: uni.getStorageSync('courierAccount')
          }
        })
        
        if (res.code === 200 && res.data && res.data.length > 0) {
          this.availableOrders = res.data
          this.availableOrderCount = res.data.length
        } else {
          // 如果没有真实数据，使用静态mock数据
          console.warn('没有获取到真实可用订单数据，使用静态mock数据')
          this.availableOrders = this.mockAvailableOrders
          this.availableOrderCount = this.mockAvailableOrders.length
        }
        
        // 重置选择状态
        this.selectedOrders = []
        this.isAllOrdersSelected = false
      } catch (err) {
        console.error('获取可接订单失败:', err)
        // 发生错误时使用静态mock数据
        this.availableOrders = this.mockAvailableOrders
        this.availableOrderCount = this.mockAvailableOrders.length
        
        uni.showToast({
          title: '获取可接订单失败，使用测试数据',
          icon: 'none'
        })
      }
    },
    async completeOrder(order) {
      try {
        const res = await request({
          url: '/courier/complete-order',
          method: 'POST',
          data: order.orderId
        })
        
        if (res.code === 200) {
          // 判断是否超时或准时，弹窗提示
          if (order.startDeliveryTime) {
            const now = Date.now();
            const start = new Date(order.startDeliveryTime).getTime();
            if (now - start > 45 * 60 * 1000) {
              uni.showModal({
                title: '提示',
                content: '订单超时，扣除20%配送费',
                showCancel: false
              });
            } else {
              uni.showModal({
                title: '提示',
                content: '准时送达，平台补贴10%配送费',
                showCancel: false
              });
            }
          }
          uni.showToast({
            title: '订单配送完成',
            icon: 'success'
          })
          
          // 刷新订单列表
          this.fetchOrderList()
        } else {
          uni.showToast({
            title: res.message || '订单配送失败',
            icon: 'none'
          })
        }
      } catch (err) {
        console.error('订单配送失败:', err)
        uni.showToast({
          title: '订单配送失败',
          icon: 'none'
        })
      }
    },
    isOrderSelected(order) {
      return this.selectedOrders.some(
        selectedOrder => selectedOrder.orderId === order.orderId
      )
    },
    toggleOrderSelection(order) {
      const index = this.selectedOrders.findIndex(
        selectedOrder => selectedOrder.orderId === order.orderId
      )
      
      if (index !== -1) {
        // 如果已选中，则取消选择
        this.selectedOrders.splice(index, 1)
      } else {
        // 如果未选中，则选择
        this.selectedOrders.push(order)
      }
      
      // 更新全选状态
      this.isAllOrdersSelected = 
        this.selectedOrders.length === this.availableOrders.length
    },
    toggleSelectAllOrders() {
      if (this.isAllOrdersSelected) {
        // 取消全选
        this.selectedOrders = []
        this.isAllOrdersSelected = false
      } else {
        // 全选
        this.selectedOrders = [...this.availableOrders]
        this.isAllOrdersSelected = true
      }
    },
    async receiveSelectedOrders() {
      if (this.selectedOrders.length === 0) return
      
      try {
        const orderIds = this.selectedOrders.map(order => order.orderId)
        console.log(orderIds)
        const res = await request({
          url: '/courier/receive-orders',
          method: 'POST',
          data: orderIds
        })
        
        if (res.code === 200) {
          uni.showToast({
            title: `成功接单 ${this.selectedOrders.length} 单`,
            icon: 'success'
          })
          
          // 刷新订单列表
          this.fetchOrderList()
          this.fetchAvailableOrders()
          
          // 重置选择状态
          this.selectedOrders = []
          this.isAllOrdersSelected = false
          // 给新接的订单加上 receiveTime 字段（前端模拟，实际建议后端返回）
          // 这里假设 fetchOrderList 后 orderList 里新接的订单没有 receiveTime，需要补充
          const now = new Date().toISOString();
          this.orderList.forEach(order => {
            if (order.status === 0 && !order.startDeliveryTime) {
              order.startDeliveryTime = now;
            }
          });
        } else {
          uni.showToast({
            title: res.message || '接单失败',
            icon: 'none'
          })
        }
      } catch (err) {
        console.error('接单失败:', err)
        uni.showToast({
          title: '接单失败',
          icon: 'none'
        })
      }
    },
    startOrderTimers() {
      // 每秒刷新一次
      this.timerInterval = setInterval(() => {
        this.$forceUpdate();
      }, 1000);
    },
    isOrderOvertime(order) {
      if (!order.startDeliveryTime) return false;
      const now = Date.now();
      const start = new Date(order.startDeliveryTime).getTime();
      return now - start > 45 * 60 * 1000;
    },
    getOrderTimerText(order) {
      if (!order.startDeliveryTime) return '';
      const now = Date.now();
      const start = new Date(order.startDeliveryTime).getTime();
      const diff = now - start;
      const limit = 45 * 60 * 1000;
      if (diff < limit) {
        // 倒计时
        const left = limit - diff;
        const min = Math.floor(left / 60000);
        const sec = Math.floor((left % 60000) / 1000);
        return `剩余 ${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
      } else {
        // 正向计时
        const over = diff - limit;
        const min = Math.floor(over / 60000);
        const sec = Math.floor((over % 60000) / 1000);
        return `超时 ${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
      }
    },
  }
}
</script>

<style scoped>
.workbench-container {
  background-color: #f4f4f4;
  min-height: 100vh;
}

.workbench-tabs {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #e0e0e0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #007AFF;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background-color: #007AFF;
}

.order-list,
.available-order-list {
  padding: 10px;
}

.order-item {
  background-color: white;
  border-radius: 10px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
}

.order-header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.order-status-bold {
  font-weight: bold;
  margin-top: 5px;
}

.order-number {
  font-weight: bold;
  color: #333;
}

.order-time {
  color: #999;
  font-size: 14px;
}

.order-content {
  margin-bottom: 10px;
}

.order-location,
.order-contact,
.order-details {
  margin-bottom: 8px;
}

.location-text {
  color: #333;
}

.contact-name,
.contact-phone {
  margin-right: 10px;
  color: #666;
}

.order-distance {
  color: #666;
}

.order-status-text {
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
}

.action-btn {
  padding: 8px 15px;
  border-radius: 5px;
  font-size: 14px;
  color: white;
}

.complete-btn {
  background-color: #007AFF;
}

.completed-btn {
  background-color: #4CD964;
}

.delayed-btn {
  background-color: #FF3B30;
}

/* 接单中心样式 */
.order-center-header {
  background-color: white;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.order-center-title {
  color: #333;
  font-weight: bold;
}

.order-item.available-order {
  position: relative;
}

.order-checkbox {
  position: absolute;
  right: 15px;
  bottom: 15px;
  transform: none;
}

.checkbox {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 2px solid #999;
  border-radius: 4px;
}

.checkbox.checked {
  background-color: #007AFF;
  border-color: #007AFF;
  position: relative;
}

.checkbox.checked::after {
  content: '✓';
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.bottom-selection-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-top: 1px solid #e0e0e0;
}

.select-all-btn {
  display: flex;
  align-items: center;
  margin-right: auto;
}

.select-all-btn .checkbox {
  margin-right: 10px;
}

.receive-all-btn {
  background-color: #007AFF;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
}

.receive-all-btn.disabled {
  background-color: #999;
  color: #ccc;
}

/* 订单状态颜色 */
.order-status-pending {
  border-left: 4px solid #007AFF;
}

.order-status-ontime {
  border-left: 4px solid #4CD964;
}

.order-status-delayed {
  border-left: 4px solid #FF3B30;
}

.available-order-list {
  padding: 10px;
  padding-bottom: 70px;
}

/* 未绑定仓库提示样式（模仿分拣员） */
.no-warehouse-tip {
  padding: 20px;
  text-align: center;
  background-color: white;
  border-radius: 10px;
  margin-bottom: 15px;
}

.tip-text {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  display: block;
}

.tip-subtitle {
  font-size: 12px;
  color: #666;
}

/* 订单卡片左下角倒计时/正计时样式 */
.order-timer-box {
  position: absolute;
  left: 16px;
  bottom: 16px;
  min-width: 80px;
  min-height: 28px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 15px;
  color: #333;
  z-index: 2;
}

.order-timer-box .overtime {
  color: #ff3b30;
  font-weight: bold;
}
</style> 